#!/bin/bash
#########################################################################
# getarch.sh用以执行一次HGWatcher.sh，然后收集HGWatcher的归档文件，
#########################################################################
basepath=$(cd `dirname $0`; pwd)
cd $basepath
hour=`date +'%Y%m%d%H%M'`
userid=`id -u`
if [[ userid -eq 0 ]];then
        :
else
        username=`whoami`
        echo -e "The current user:$username"
        echo 'Please use the root run the script!'
        exit 1
fi
pro=`ps -ef | grep HGWatcher | grep -v grep | awk '{print $2}'`
if test -n "$pro"
then
  ps -ef | grep HGWatcher | grep -v grep | awk '{print $2}' | xargs kill -15
else
  rm -f $basepath/tmp/last.sh
fi
sleep 5

if [ -f $basepath/tmp/last.sh ];then
  last=`cat $basepath/tmp/last.sh`
  $last -check true
else
  if [ -f $basepath/data/dblist.cfg ];then
    ./HGWatcher.sh -check true
  else
    ./getDBlist.sh
  fi
fi

while true
do
  pro=`ps -ef | grep HGWatcher | grep -v grep | awk '{print $2}'`
  if test -n "$pro"
  then
    :
  else
    HGW_ARCHIVE_DEST=`cat $basepath/tmp/HGW.hb`
    DBLIST=`cat $basepath/tmp/dblist.dir`
    if test -n "$DBLIST" && test -f "$DBLIST"
    then
      for i in $(grep DATABASE  $DBLIST|grep -v END | grep -o "[0-9]\{1,3\}")
      do
        DATABASEN="DATABASE$i"
        ENDDATABASEN="END"$DATABASEN
        logdir=`awk '/\['$DATABASEN'\]/,/\['$ENDDATABASEN'\]/ {print}' $DBLIST |grep log_directory|awk -F '=' '{print $2}'`
        pgport=`awk '/\['$DATABASEN'\]/,/\['$ENDDATABASEN'\]/ {print}' $DBLIST |grep PGPORT|awk -F '=' '{print $2}'`
        mkdir -p $HGW_ARCHIVE_DEST/pglog/$pgport
        find $logdir -type f -mtime -7 -exec cp {} $HGW_ARCHIVE_DEST/pglog/$pgport/ \;
        mkdir -p $HGW_ARCHIVE_DEST/SystemInfo
        lsb_release -d >$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        echo -e '\nhosts' >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        cat /etc/hosts >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        echo -e '\nSystem operation information' >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        uptime >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        echo -e '\nFirewall configuration' >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        iptables -L >>$HGW_ARCHIVE_DEST/SystemInfo/systeminfo.txt
        cp /var/log/messages* $HGW_ARCHIVE_DEST/SystemInfo/
       # cp /var/log/yum.log* $HGW_ARCHIVE_DEST/SystemInfo/
      done
    fi
    tar -czf HGWatcher_archive_$hour.tar.gz $HGW_ARCHIVE_DEST 2>/dev/null
    echo -e "\033[32m##########################################################################################\033[0m"
    echo -e "\033[32m#       The output file is $basepath/HGWatcher_archive_$hour.tar.gz\033[0m"
    echo -e "\033[32m##########################################################################################\033[0m"
    if [ -n $last ];then
      $last
    fi
    exit 0
  fi
  sleep 1
done

